#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <thread>
#include <atomic>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <queue>

// 简单的无锁栈实现（移到全局作用域）
template<typename T>
class LockFreeStack {
private:
    struct Node {
        T data;
        Node* next;
        Node(const T& item) : data(item), next(nullptr) {}
    };
    
    std::atomic<Node*> head{nullptr};
    
public:
    void push(const T& item) {
        Node* new_node = new Node(item);
        new_node->next = head.load();
        while (!head.compare_exchange_weak(new_node->next, new_node)) {
            // CAS失败，重试
        }
    }
    
    bool pop(T& result) {
        Node* old_head = head.load();
        while (old_head && !head.compare_exchange_weak(old_head, old_head->next)) {
            // CAS失败，重试
        }
        
        if (old_head) {
            result = old_head->data;
            delete old_head;
            return true;
        }
        return false;
    }
    
    ~LockFreeStack() {
        T dummy;
        while (pop(dummy)) {
            // 清理所有节点
        }
    }
};

/**
 * 线程安全测试类
 * 测试多线程环境下的安全性和同步机制
 */
class ThreadSafetyTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 测试环境初始化
    }

    void TearDown() override {
        // 测试环境清理
    }
};

/**
 * 测试原子操作的线程安全性
 */
TEST_F(ThreadSafetyTest, TestAtomicOperations) {
    const int NUM_THREADS = 4;
    const int OPERATIONS_PER_THREAD = 10000;
    
    std::atomic<int> counter(0);
    std::atomic<long> sum(0);
    std::vector<std::thread> threads;
    
    // 启动多个线程进行原子操作
    for (int t = 0; t < NUM_THREADS; ++t) {
        threads.emplace_back([&counter, &sum, OPERATIONS_PER_THREAD, t]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                counter.fetch_add(1);
                sum.fetch_add(t * 1000 + i);
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证原子操作结果
    EXPECT_EQ(counter.load(), NUM_THREADS * OPERATIONS_PER_THREAD);
    
    // 验证累加结果
    long expected_sum = 0;
    for (int t = 0; t < NUM_THREADS; ++t) {
        for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
            expected_sum += t * 1000 + i;
        }
    }
    EXPECT_EQ(sum.load(), expected_sum);
}

/**
 * 测试互斥锁的线程安全性
 */
TEST_F(ThreadSafetyTest, TestMutexSafety) {
    const int NUM_THREADS = 4;
    const int OPERATIONS_PER_THREAD = 1000;
    
    int shared_counter = 0;
    std::mutex counter_mutex;
    std::vector<std::thread> threads;
    
    // 启动多个线程进行互斥访问
    for (int t = 0; t < NUM_THREADS; ++t) {
        threads.emplace_back([&shared_counter, &counter_mutex, OPERATIONS_PER_THREAD]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                std::lock_guard<std::mutex> lock(counter_mutex);
                shared_counter++;
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证互斥锁保护的共享数据
    EXPECT_EQ(shared_counter, NUM_THREADS * OPERATIONS_PER_THREAD);
}

/**
 * 测试读写锁的性能和安全性（使用普通互斥锁模拟）
 */
TEST_F(ThreadSafetyTest, TestReaderWriterLock) {
    const int NUM_READERS = 8;
    const int NUM_WRITERS = 2;
    const int OPERATIONS_PER_THREAD = 100;
    
    int shared_data = 0;
    std::mutex rw_mutex; // 使用普通互斥锁代替shared_mutex
    std::atomic<int> read_count(0);
    std::atomic<int> write_count(0);
    std::vector<std::thread> threads;
    
    // 启动读者线程
    for (int r = 0; r < NUM_READERS; ++r) {
        threads.emplace_back([&shared_data, &rw_mutex, &read_count, OPERATIONS_PER_THREAD]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                std::lock_guard<std::mutex> lock(rw_mutex);
                int value = shared_data; // 读取共享数据
                read_count.fetch_add(1);
                
                // 模拟读取操作的处理时间
                std::this_thread::sleep_for(std::chrono::microseconds(1));
                
                // 验证数据一致性（读取的值应该是非负的）
                EXPECT_GE(value, 0);
            }
        });
    }
    
    // 启动写者线程
    for (int w = 0; w < NUM_WRITERS; ++w) {
        threads.emplace_back([&shared_data, &rw_mutex, &write_count, OPERATIONS_PER_THREAD, w]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                std::lock_guard<std::mutex> lock(rw_mutex);
                shared_data = w * 1000 + i; // 写入共享数据
                write_count.fetch_add(1);
                
                // 模拟写入操作的处理时间
                std::this_thread::sleep_for(std::chrono::microseconds(5));
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证操作计数
    EXPECT_EQ(read_count.load(), NUM_READERS * OPERATIONS_PER_THREAD);
    EXPECT_EQ(write_count.load(), NUM_WRITERS * OPERATIONS_PER_THREAD);
    
    // 验证最终数据状态
    EXPECT_GE(shared_data, 0);
}

/**
 * 测试条件变量的线程同步
 */
TEST_F(ThreadSafetyTest, TestConditionVariable) {
    const int NUM_PRODUCERS = 2;
    const int NUM_CONSUMERS = 3;
    const int ITEMS_PER_PRODUCER = 100;
    
    std::queue<int> buffer;
    std::mutex buffer_mutex;
    std::condition_variable not_empty;
    std::condition_variable not_full;
    const size_t MAX_BUFFER_SIZE = 10;
    
    std::atomic<int> produced_count(0);
    std::atomic<int> consumed_count(0);
    std::atomic<bool> production_done(false);
    
    std::vector<std::thread> threads;
    
    // 启动生产者线程
    for (int p = 0; p < NUM_PRODUCERS; ++p) {
        threads.emplace_back([&, p]() {
            for (int i = 0; i < ITEMS_PER_PRODUCER; ++i) {
                std::unique_lock<std::mutex> lock(buffer_mutex);
                
                // 等待缓冲区有空间
                not_full.wait(lock, [&]() { return buffer.size() < MAX_BUFFER_SIZE; });
                
                // 生产数据
                int item = p * 1000 + i;
                buffer.push(item);
                produced_count.fetch_add(1);
                
                // 通知消费者
                not_empty.notify_one();
            }
        });
    }
    
    // 启动消费者线程
    for (int c = 0; c < NUM_CONSUMERS; ++c) {
        threads.emplace_back([&]() {
            while (true) {
                std::unique_lock<std::mutex> lock(buffer_mutex);
                
                // 等待缓冲区有数据或生产完成
                not_empty.wait(lock, [&]() { 
                    return !buffer.empty() || production_done.load(); 
                });
                
                if (buffer.empty() && production_done.load()) {
                    break; // 生产完成且缓冲区为空，退出
                }
                
                if (!buffer.empty()) {
                    // 消费数据
                    int item = buffer.front();
                    buffer.pop();
                    consumed_count.fetch_add(1);
                    
                    // 通知生产者
                    not_full.notify_one();
                    
                    // 验证消费的数据
                    EXPECT_GE(item, 0);
                }
            }
        });
    }
    
    // 等待生产者完成
    for (int i = 0; i < NUM_PRODUCERS; ++i) {
        threads[i].join();
    }
    
    // 标记生产完成
    production_done.store(true);
    not_empty.notify_all();
    
    // 等待消费者完成
    for (int i = NUM_PRODUCERS; i < NUM_PRODUCERS + NUM_CONSUMERS; ++i) {
        threads[i].join();
    }
    
    // 验证生产和消费的数量
    EXPECT_EQ(produced_count.load(), NUM_PRODUCERS * ITEMS_PER_PRODUCER);
    EXPECT_EQ(consumed_count.load(), NUM_PRODUCERS * ITEMS_PER_PRODUCER);
    EXPECT_TRUE(buffer.empty());
}

/**
 * 测试线程局部存储
 */
TEST_F(ThreadSafetyTest, TestThreadLocalStorage) {
    const int NUM_THREADS = 4;
    const int OPERATIONS_PER_THREAD = 1000;
    
    thread_local int tls_counter = 0;
    std::vector<std::thread> threads;
    std::vector<int> final_values(NUM_THREADS);
    
    // 启动多个线程，每个线程操作自己的线程局部变量
    for (int t = 0; t < NUM_THREADS; ++t) {
        threads.emplace_back([&final_values, t, OPERATIONS_PER_THREAD]() {
            // 初始化线程局部变量
            tls_counter = t * 100;
            
            // 对线程局部变量进行操作
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                tls_counter++;
            }
            
            // 保存最终值
            final_values[t] = tls_counter;
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证每个线程的线程局部变量值
    for (int t = 0; t < NUM_THREADS; ++t) {
        int expected_value = t * 100 + OPERATIONS_PER_THREAD;
        EXPECT_EQ(final_values[t], expected_value);
    }
}

/**
 * 测试无锁数据结构
 */
TEST_F(ThreadSafetyTest, TestLockFreeDataStructure) {
    const int NUM_THREADS = 4;
    const int OPERATIONS_PER_THREAD = 1000;
    
    LockFreeStack<int> stack;
    std::atomic<int> push_count(0);
    std::atomic<int> pop_count(0);
    std::vector<std::thread> threads;
    
    // 启动推送线程
    for (int t = 0; t < NUM_THREADS / 2; ++t) {
        threads.emplace_back([&stack, &push_count, OPERATIONS_PER_THREAD, t]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                stack.push(t * 1000 + i);
                push_count.fetch_add(1);
            }
        });
    }
    
    // 启动弹出线程
    for (int t = NUM_THREADS / 2; t < NUM_THREADS; ++t) {
        threads.emplace_back([&stack, &pop_count, OPERATIONS_PER_THREAD]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                int value;
                if (stack.pop(value)) {
                    pop_count.fetch_add(1);
                    EXPECT_GE(value, 0); // 验证弹出的值
                } else {
                    // 栈为空，稍等再试
                    std::this_thread::sleep_for(std::chrono::microseconds(1));
                    i--; // 重试
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证操作计数
    EXPECT_EQ(push_count.load(), (NUM_THREADS / 2) * OPERATIONS_PER_THREAD);
    EXPECT_EQ(pop_count.load(), (NUM_THREADS / 2) * OPERATIONS_PER_THREAD);
}
